<template>
	<view class="content">
		<form class="form-input" @submit="formSubmit" >
		<view class="row b-b">
			<text class="tit">联系人</text>
			<input class="input" type="text" name="name" v-model="addressData.name" placeholder="收货人姓名" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input class="input" type="number" name="phoneNum" v-model="addressData.mobile" placeholder="收货人手机号码" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">地址</text>
			<input type="text" 
			v-model="addressData.address"  
			name="address"  
			
			class="input"   
			placeholder="请在地图上选择" />
			
			<text class="yticon icon-shouhuodizhi" @click="chooseLocation" ></text>
		</view>
		<view class="row b-b"> 
			<text class="tit">门牌号</text>
			<input class="input" type="text" name="number" v-model="addressData.area" placeholder="楼号、门牌" placeholder-class="placeholder" />
		</view>
		
		<view class="row default-row">
			<text class="tit">设为默认</text>
			<switch :checked="switchcheck" name="num"  color="#fa436a" @click="switchClick" />
		</view>
		<button class="add-btn"  type="primary" formType="submit"   >提交</button>
		</form>
	</view>
</template>

<script>
	//来自 graceUI 的表单验证， 使用说明见手册 http://grace.hcoder.net/doc/info/73-3.html
	var  graceChecker = require("../../common/graceChecker.js");
	export default {
		data() {
			return {
				addressData: {
					id: ''
				},
				type: ''
			}
		},
		onLoad(option){
			this.type = option.type;
			this.addressData.default = false;
			let title = '新增收货地址';
			if(option.type==='edit'){
				title = '编辑收货地址'
				// this.addressData = JSON.parse(option.data)
				let item = JSON.parse(option.data)
				this.loadDate(item)
			}
			this.manageType = option.type;
			uni.setNavigationBarTitle({
				title
			})
			uni.startPullDownRefresh();
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		computed: {
			switchcheck : function(){
				return this.addressData.default
			} 
		},
		methods: {
			loadDate(item){
				this.addressData.id = item.ID
				this.addressData.name = item.LINKNAME
				this.addressData.mobile = item.TEL
				var array = item.ADDRESS.split("-")
				this.addressData.address = array[0]
				this.addressData.area =  array[1]
				this.addressData.default = item.ISDEFAULT
				
			},
			//表单校验
			formSubmit(e) {
				// 将下列代码加入到对应的检查位置
				// 定义表单规则
				var rule = [
					{name:"name", checkType : "notnull",  errorMsg:"请输入收货人名称"},
					{name:"phoneNum", checkType : "phoneno",  errorMsg:"请输入正确的手机号"},
					{name:"address", checkType : "notnull",  errorMsg:"请输入收货人地址"},
					{name:"number", checkType : "notnull",  errorMsg:"请输入门牌号"},
				];
				//进行表单检查
				var formData = e.detail.value;
				var checkRes = graceChecker.check(formData, rule);
				if(checkRes){
					
					if(this.type === 'add'){
						//添加方法
						this.$http.post("/user/addAddress",{
							SIGNATURE : uni.getStorageSync("SIGNATURE"),
							TOKEN: uni.getStorageSync('userInfo').TOKEN,
							LINKNAME: this.addressData.name,
							TEL: this.addressData.mobile,
							ADDRESS: this.addressData.address + "-" + this.addressData.area,
							ISDEFAULT: this.addressData.default ? 1 : 0,
						}).then(res=>{
							console.log(res);
							if(res.data.STATE == '903'||res.data.STATE == '904'){
								// #ifdef MP-WEIXIN
								uni.showModal({
									content:'请先登录',
									success: function (res) {
									        if (res.confirm) {
									            uni.switchTab({
									            	url:"/pages/user/user"
									            })
									        } else if (res.cancel) {
									            console.log('用户点击取消');
									        }
									    }
								})
								// #endif
								// #ifndef MP-WEIXIN
								uni.navigateTo({
									url: "/pages/public/login1"
								})
								// #endif
								
							}
							if(res.data.STATE === '0' && res.statusCode === 200){
								//页面返回并刷新  
								uni.navigateBack();
							}
						}).catch(err =>{
							console.log('request fail', err);
						})
					}else{
						//修改逻辑
						this.$http.post("/user/updateAddress",{
							ADDRESSID : this.addressData.id,
							SIGNATURE : uni.getStorageSync("SIGNATURE"),
							TOKEN: uni.getStorageSync('userInfo').TOKEN,
							LINKNAME: this.addressData.name,
							TEL: this.addressData.mobile,
							ADDRESS: this.addressData.address + "-" + this.addressData.area,
							ISDEFAULT: this.addressData.default ? 1 : 0,
						}).then(res=>{
							console.log(res);
							if(res.data.STATE === '0' && res.statusCode === 200){
							
								
								//页面跳转   
								uni.navigateBack();
							}
						}).catch(err =>{
							console.log('request fail', err);
						})
					}
				}else{
					uni.showToast({ title: graceChecker.error, icon: "none" });
				}
			},
			switchClick(){
				this.addressData.default = !this.addressData.default;
			},
			//地图选择地址
			chooseLocation(){
				
				uni.chooseLocation({
					success: (data)=> {
						console.log("666666",data)
						this.addressData.addressName = data.name;
						this.addressData.address = data.name;
					}
				});
				
			},
			//提交
			confirm(){
				let data = this.addressData;
				if(!data.name){
					this.$api.msg('请填写收货人姓名');
					return;
				}
				if(!/(^1[3|4|5|7|8][0-9]{9}$)/.test(data.mobile)){
					this.$api.msg('请输入正确的手机号码');
					return;
				}
				if(!data.address){
					this.$api.msg('请在地图选择所在位置');
					return;
				}
				if(!data.area){
					this.$api.msg('请填写门牌号信息');
					return;
				}
				
				//this.$api.prePage()获取上一页实例，可直接调用上页所有数据和方法，在App.vue定义
				this.$api.prePage().refreshList(data, this.manageType);
				this.$api.msg(`地址${this.manageType=='edit' ? '修改': '添加'}成功`);
				setTimeout(()=>{
					uni.navigateBack()
				}, 800)
			},
		}
	}
</script>

<style lang="scss">
	page{
		background: $page-color-base;
		padding-top: 16upx;
	}

	.row{
		display: flex;
		align-items: center;
		position: relative;
		padding:0 30upx;
		height: 110upx;
		background: #fff;
		
		.tit{
			flex-shrink: 0;
			width: 120upx;
			font-size: 30upx;
			color: $font-color-dark;
		}
		.input{
			flex: 1;
			font-size: 30upx;
			color: $font-color-dark;
		}
		.icon-shouhuodizhi{
			font-size: 36upx;
			color: $font-color-light;
		}
	}
	.default-row{
		margin-top: 16upx;
		.tit{
			flex: 1;
		}
		switch{
			transform: translateX(16upx) scale(.9);
		}
	}
	.add-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690upx;
		height: 80upx;
		margin: 60upx auto;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
</style>
